//
//  JXUserAcountViewModel.swift
//  01-weiboSwift
//
//  Created by TwistFate on 16/2/28.
//  Copyright © 2016年 TwistFate. All rights reserved.
//

import UIKit

class JXUserAcountViewModel: NSObject {
    
    static let sharedInstance : JXUserAcountViewModel = JXUserAcountViewModel()
    
    var userAcount : JXUserAccount?
    
    var isUserLogin : Bool {
        get{
            return userAcount != nil
        }
    }
    
    let docPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/userAcount.plist")
    
    private override init() {
        super.init()
        userAcount = loadUserAcount()
    }

    func loadUserAcount(code : String , loadAccessTokenCallBack : (error : NSError?) -> ()) {
        JXNetworkTool.sharedInstance.loadAccessToken(code, accessTokenFinished: { (response, error) -> () in
//            error = NSError(domain: "1", code: 1, userInfo: nil)
            if error != nil {
                print("accessToken授权时失败error:\(error)")
                loadAccessTokenCallBack(error: error)
                return
            }
            
            
            print("accessToken授权时成功response:\(response)")
            self.userAcount = JXUserAccount(dict: response!)
            
            self.saveUserAcount()
            
            loadAccessTokenCallBack(error: nil)
        })
    }
    
    func saveUserAcount () {
        if userAcount != nil {
//            print("docPath:\(docPath)")
            NSKeyedArchiver.archiveRootObject(userAcount!, toFile: docPath!)
        }
    }
    
    func loadUserAcount () -> JXUserAccount? {
         let acount = NSKeyedUnarchiver.unarchiveObjectWithFile(docPath!) as? JXUserAccount
        
        if acount != nil && acount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending
        {
            return acount
        }else{
            return nil
        }
    }
    
    func loadUserInfo (loadUserInfoCallBack :(error : NSError?) -> ()) {
    
        JXNetworkTool.sharedInstance.loadUserInfo { (result, error) -> () in
            if error != nil{
                
                loadUserInfoCallBack(error: error)
                return
            }
            
//            print("加载用户数据成功:\(result)")
            
            self.userAcount?.screen_name = result?["screen_name"] as? String
            self.userAcount?.avatar_large = result?["avatar_large"] as? String
            
            loadUserInfoCallBack(error: nil)
            
            self.saveUserAcount()
        }
    }
}
